//
//  UserAccountViewModel.swift
//  weibo
//
//  Created by 黄龙飞 on 15/11/26.
//  Copyright © 2015年 黄龙飞. All rights reserved.
//

import Foundation
class UserAccountViewModel {
    ///token字典
    var tokenDict:[String:AnyObject]?{
        return isExpired ? nil :["access_token":account!.access_token!]
    }
    
    static let sharedUserAccount=UserAccountViewModel()
    var account :UserAccount?
    
    
    //登录过期判断
    var userLogon :Bool{
    return account?.access_token != nil && !isExpired
    }
    private var isExpired:Bool{
//        account?.expiresDate=NSDate(timeIntervalSinceNow: -3600)
        if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            //降序
        return false
        }
        return true
    }
    
    private var accountPath:String{
        let path=NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }
    init(){
        account=NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        if isExpired{
        print("已经过期了")
            account = nil
        }
        print(account)
    }
    
}

extension UserAccountViewModel{
    func loadAccessToken(code:String,finished:(isSuccessed:Bool)->()){
    // 4. 加载 accessToken
    NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
    
    // 1> 判断错误
    if error != nil {
    finished(isSuccessed: false)
    return
    }
       
    // 2> 输出结果
    print(result)
    self.account=UserAccount(dict: result as! [String:AnyObject])
    self.loadUserInfo(self.account!,finished: finished)
    }
 }
    
    //加载用户信息
    private func loadUserInfo(account: UserAccount, finished:(isSuccessed:Bool)->()){
        NetworkTools.sharedTools.loadUserInfo(account.uid!){
            (result,error)->() in
            if error != nil{
                finished(isSuccessed: false)
                return
            }
            guard let dict = result as?[String: AnyObject] else{
                print("格式错误")
                finished(isSuccessed: false)
                return
            }
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            print(account)
            finished(isSuccessed: true)
        }
    }
}